<template>
  <div>
    <div>
      <!-- check-strictly="true" 取消父子相关联 -->
      <el-tree
        ref="tree"
        v-loading="loading"
        :data="permissionList"
        default-expand-all
        :props="{ label: 'name'}"
        show-checkbox
        check-strictly
        node-key="id"
      />
    </div>

    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="cancelButton">取 消</el-button>
        <el-button size="small" type="primary" @click="setRolesBtn">确 定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// 导入获取权限列表的API
import { getPermissionList } from '@/api/permission'

import { getRoleId, assignPerm } from '@/api/setting'

// 导入扁平数组转树形数组的方法
import { tranListToTreeData } from '@/utils'

export default {
  name: 'AssignPermission',

  props: {
    roleId: {
      type: [Number, String],
      required: true
    }
  },

  data() {
    return {
      permissionList: [],
      loading: false
    }
  },

  created() {
    // 调用获取权限列表方法
    this.getPermissionList()

    // 调用根据id获取角色已有权限
    this.getRoleId()
  },

  methods: {
    // 根据id获取角色已有权限
    async getRoleId() {
      const res = await getRoleId(this.roleId)
      console.log(res)
      this.$refs.tree.setCheckedKeys(res.data.permIds)
      // console.log(res.data.permIds)
    },

    // 获取权限列表的方法
    async getPermissionList() {
      const res = await getPermissionList()
      this.permissionList = tranListToTreeData(res.data)
    },

    cancelButton() {
      this.$emit('close')
    },

    // 分配权限
    async setRolesBtn() {
      const permIds = this.$refs.tree.getCheckedKeys()
      const res = await assignPerm({ id: this.roleId, permIds })

      // 给用户提示
      this.$message.success(res.message)

      this.$emit('close')
    }

  }
}
</script>

<style lang="scss" scoped>
.footer{
    margin-top: 30px;
}
</style>
